<?php
declare (strict_types = 1);

namespace app\store\middleware;

use think\facade\View;
use app\store\service\AdminService;

class Auth
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //
        $user_id = session('user_id');
        if(!$user_id){
            return redirect('/store/login');
        }
        $adminService = new AdminService();

        $menus = $adminService->getMenuList($user_id);

        if(empty($menus)){
            return redirect('/store/login');
        }

        $currentRule = app('http')->getName() . '@' . request()->controller(true) . '@' . request()->action(true);


        $result = $this->checkPermission($menus,$currentRule);
        $request->allowed = $result;


        View::assign('allowed',$result);
        
        // 生成菜单
        $data = $this->generateTreeMenu($menus,$currentRule);

        View::assign('menus',$data);
        
        return $next($request);
    }

    // 检查用户权限
    protected function checkPermission($menus,$currentRule)
    {   
        $rule = array_column($menus,'node');

        //halt($currentRule);
        $result = in_array($currentRule,$rule);

        return  $result;
    }


    // 生成系统菜单
    protected function generateTreeMenu($array,$currentRule)
    {
        //第一步 构造数据
        $items = array();
        foreach ($array as $value) {
            if ($value['node'] == $currentRule){
                $value['selected'] = 1;
            } else{
                $value['selected'] = 0;
            }

            $items[$value['id']] = $value;
        }

        //第二步 遍历数据 生成树状结构
        $tree = array();
        foreach ($items as $key => $item) {
            //若不是顶级分类，则将其本身作为son放置在父类中，
            //注意：此时放置的是引用，
            //也就是说，当儿子再次出现儿子的时候，儿子与孙子重新组合成父亲与儿子的形象
            //但是，在顶级父类中存放的是儿子的引用，所以，当儿子与孙子被重新组合时，顶级父类中也被修改
            if (isset($items[$item['parent_id']])) {
                $items[$item['parent_id']]['children'][] = &$items[$key];
            } else {
                $tree[] = &$items[$key];
            }
        }
        return $tree;
    }


}
